<?php

namespace App\Http\Controllers\Company;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CompanyAdminModel;
use App\Models\CompanyModel;
use App\Tools\Fun;

class CompanyAdminController extends Controller {
    public function login(Request $request) {
        $username = $request->input('username');
        $password = $request->input('password');
        $company = $request->input('company');

        $res = CompanyAdminModel::login($company, $username, $password); // Llama al método login de CompanyModel
        if($res['code'] != 200) 
            return self::sendError($res['msg'], $res['code']);

        return self::sendOk(['token' => $res['token']], "Login successful", 200);
    }

    public function logout(Request $request) {
        CompanyAdminModel::logout($request->company_admin_id); // Llama al método logout de CompanyModel
        return self::sendOk([], "Logout successful", 200); // Asegúrate de que sendOk esté definido en tu controlador base o úti
    }

    public function info(Request $request) {

        $companyId = $request->company_id;
        $adminId = $request->company_admin_id;
        $company = CompanyModel::find($companyId);
        $admin = CompanyAdminModel::find($adminId);
        $admin->roles = ['admin'];
        $admin->introduction = "I am a super administrator";
        $data = [
            'company' => $company,
            'admin' => $admin
        ];
        return self::sendOk($data, "Company admin info", 200); // Asegúrate de que sendOk esté definido en tu controlador base o úti
    }

    // 对管理员进行管理
    public function managers(Request $request) {
        $companyId = $request->company_id;
        $managers = CompanyAdminModel::where('company_id', $companyId)->get(); // Llama al método managers de CompanyModel
        return self::sendOk($managers, "Company managers", 200); // Asegúrate de que sendOk esté definido en tu controlador base o úti
    }

    public function saveManager(Request $request) {
        $adminId = $request->id;
        $password = $request->password;
        if ($adminId)  // Actualizar administrador existente
            $admin = CompanyAdminModel::find($adminId);
        else 
            $admin = new CompanyAdminModel;
        $admin->fill($request->only('username', 'realname', 'phone'));
        $admin->password = $password == $admin->password ? $password : Fun::encodePassword($password);
        $admin->company_id = $request->company_id;
        $admin->save();
        return self::sendOk($admin, "Manager saved", 200);
    }

    public function deleteManager(Request $request) {
        $companyId = $request->company_id;
        $managerId = $request->manager_id;
        $res = CompanyAdminModel::deleteManager($companyId, $managerId); // Llama al método deleteManager de CompanyModel
        if($res['code']!= 200)
            return self::sendError($res['msg'], $res['code']);
    }
}